using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;

namespace CSharpPro._1106
{
    public class UserServiceImpl : IUserService
    {
        private readonly List<User> _users = new List<User>();

        public void ShowMenu()
        {
            while (true)
            {
                Console.WriteLine("\n主菜单:");
                Console.WriteLine("1. 登录");
                Console.WriteLine("2. 注册");
                Console.WriteLine("3. 列表");
                Console.WriteLine("4. 删除用户");
                Console.WriteLine("5. 退出");
                Console.Write("请选择 (1-5): ");

                var input = Console.ReadLine();
                if (!int.TryParse(input, out int choice))
                {
                    Console.WriteLine("请输入有效数字");
                    continue;
                }

                switch (choice)
                {
                    case 1:
                        DoLoginInteractive();
                        break;
                    case 2:
                        DoRegisterInteractive();
                        break;
                    case 3:
                        ListUsers();
                        break;
                    case 4:
                        DoDeleteInteractive();
                        break;
                    case 5:
                        return;
                    default:
                        Console.WriteLine("无效选项");
                        break;
                }
            }
        }

        public bool Register(User user)
        {
            // 简单校验和重复检查，使用 foreach 迭代集合
            if (string.IsNullOrWhiteSpace(user?.Username) || string.IsNullOrWhiteSpace(user?.Password))
                return false;

            foreach (var u in _users)
            {
                if (u.Username.Equals(user.Username, StringComparison.OrdinalIgnoreCase))
                    return false;
            }

            _users.Add(user);
            return true;
        }

        public bool Login(string username, string password)
        {
            foreach (var u in _users)
            {
                if (u.Username.Equals(username, StringComparison.OrdinalIgnoreCase) && u.Password == password)
                    return true;
            }
            return false;
        }

        public void ListUsers()
        {
            Console.WriteLine("\n已注册用户：");
            if (_users.Count == 0)
            {
                Console.WriteLine("（无用户）");
                return;
            }

            foreach (var u in _users)
            {
                Console.WriteLine($"- {u.Username}");
            }
        }

        public bool DeleteUser(string username)
        {
            // 使用 for 循环删除，确保安全
            for (int i = 0; i < _users.Count; i++)
            {
                if (_users[i].Username.Equals(username, StringComparison.OrdinalIgnoreCase))
                {
                    _users.RemoveAt(i);
                    return true;
                }
            }
            return false;
        }

        // ----- 交互方法（用于菜单） -----
        private void DoRegisterInteractive()
        {
            Console.Write("请输入用户名: ");
            var username = Console.ReadLine()?.Trim();
            if (string.IsNullOrEmpty(username))
            {
                Console.WriteLine("用户名不可为空");
                return;
            }
            if (username.Length < 3 || username.Length > 15)
            {
                Console.WriteLine("用户名长度必须为3-15个字符");
                return;
            }
            if (!Regex.IsMatch(username, @"^[a-zA-Z0-9_]+$"))
            {
                Console.WriteLine("用户名只能包含字母、数字和下划线");
                return;
            }

            Console.Write("请输入密码: ");
            var password = Console.ReadLine()?.Trim();
            if (string.IsNullOrEmpty(password) || password.Length < 6)
            {
                Console.WriteLine("密码太短");
                return;
            }

            var user = new User(username, password);
            if (Register(user))
                Console.WriteLine("注册成功！");
            else
                Console.WriteLine("注册失败（用户名可能已存在）");
        }

        private void DoLoginInteractive()
        {
            Console.Write("用户名: ");
            var username = Console.ReadLine()?.Trim();
            Console.Write("密码: ");
            var password = Console.ReadLine()?.Trim();

            if (Login(username, password))
                Console.WriteLine("登录成功！");
            else
                Console.WriteLine("登录失败，用户名或密码错误");
        }

        private void DoDeleteInteractive()
        {
            Console.Write("请输入要删除的用户名: ");
            var username = Console.ReadLine()?.Trim();
            if (DeleteUser(username))
                Console.WriteLine("删除成功");
            else
                Console.WriteLine("未找到该用户");
        }
    }
}
